<?php

class Zdl extends Controller
{

    public function __construct()
    {
        parent::__construct();
        if (!Identity::getInstance()->isLoggedIn()) redirect('auth');

        $this->load->model('post_model');
    }

    public function index()
    {
        $this->load->view('zdl/index_view', array());
    }

    public function top()
    {
        $this->load->view('zdl/top_view', array());
    }

    public function pmd()
    {
        $allPosts = $this->post_model->getPosts();

        $memberNoti = array();
        $memberHistory = array();
        $notiNews = array();
        $notiHistory = array();

        foreach ($allPosts as $post) {

            if ($post['type'] == '1') {
                $memberNoti[] = $post;
            } elseif ($post['type'] == '2') {
                $notiNews[] = $post;
            } elseif ($post['type'] == '3') {
                $memberHistory[] = $post;
            } else {
                $notiHistory[] = $post;
            }
        }

        $data = array(
            'memberNoti' => $memberNoti,
            'memberHistory' => $memberHistory,
            'notiNews' => $notiNews,
            'notiHistory' => $notiHistory
        );

        $this->load->view('zdl/pmd_view', $data);
    }

    public function editPost()
    {

        if (Identity::getInstance()->getRole() != '-1') {
            echo 'error';
            die();
        }

        $val = trim($this->input->post('ns', TRUE));
        $edit = $this->input->post('edit', TRUE);
        $id = $this->input->post('id', TRUE);

        if ($val == '') {
            echo 'error';
            die();
        }

        $arrEdit = array();
        $arrEdit[$edit] = $val;

        if ($this->post_model->editPosts(
            $arrEdit, array(
                'id' => $id
            )
        )
        ) {

            echo $val;
        } else {

            echo 'error';
        }
    }

    public function addPost()
    {
        $data = array(
            'status' => 0,
            'error' => ''
        );

        if (Identity::getInstance()->getRole() == '-1') {

            $content = trim($this->input->post('content', TRUE));
            $time = trim($this->input->post('time', TRUE));
            $type = $this->input->post('type', TRUE);

            if ($content != '' && $time != '') {

                if ($this->post_model->addPost(array(
                    'content' => $content,
                    'time' => $time,
                    'type' => $type
                ))
                ) {

                    $data['status'] = 1;
                }
            }
        }

        echo json_encode($data);
    }

    public function delPost($id)
    {

        if (Identity::getInstance()->getRole() == '-1') {

            $this->post_model->delPost($id);
        }

        redirect('zdl');
    }

    public function report()
    {
        $this->load->view('zdl/report_view', array());
    }

}
